package com.jushu.storbox.adapter;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import android.app.ActionBar.LayoutParams;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jushu.storbox.FileDownloadActivity;
import com.jushu.storbox.ImageViewActivity;
import com.jushu.storbox.R;
import com.jushu.storbox.ShareDriveApplication;
import com.jushu.storbox.ShareDriveMainFragmentActivity;
import com.jushu.storbox.ShareFileSearchActivity;
import com.jushu.storbox.actions.Actions;
import com.jushu.storbox.actions.MoveAction;
import com.jushu.storbox.callback.IDownloadCallback;
import com.jushu.storbox.callback.IDownloadThumbnailCallback;
import com.jushu.storbox.constant.ClientConfig;
import com.jushu.storbox.constant.Constant;
import com.jushu.storbox.constant.MessageCode;
import com.jushu.storbox.constant.UiConstant;
import com.jushu.storbox.database.DAOFactory;
import com.jushu.storbox.entities.FileFolderInfo;
import com.jushu.storbox.entities.FileInfo;
import com.jushu.storbox.entities.FolderInfo;
import com.jushu.storbox.entities.SharedUser;
import com.jushu.storbox.filesystem.FileManagerFactory;
import com.jushu.storbox.filesystem.iFileManager;
import com.jushu.storbox.fragment.AllFileFragment;
import com.jushu.storbox.handler.ClientExceptionRelateHandler;
import com.jushu.storbox.network.WifiController;
import com.jushu.storbox.service.ICloudDriveService;
import com.jushu.storbox.task.GetShareUserAsyncTask;
import com.jushu.storbox.task.tqueue.DownloadTask;
import com.jushu.storbox.util.DirectoryUtil;
import com.jushu.storbox.util.LogUtil;
import com.jushu.storbox.util.PublicTools;
import com.jushu.storbox.view.dialog.ClouddriveDialog;
import com.jushu.storbox.view.viewImpl.PinProgressButton;
import com.huawei.sharedrive.sdk.android.exception.ClientException;
import com.huawei.sharedrive.sdk.android.service.CommonClient;

public class MyFileListAdapter extends BaseAdapter {
	private final static String LOG_TAG = "MyFileListAdapter";

	private Context context;

	private Handler handlerRefurbish;

	private LayoutInflater mInflater;

	public List<FileFolderInfo> fileList;

	private String timeInfo;

	private ICloudDriveService cloudDriveService;

	private ProgressBar downlonProgressBar;

	private String TAG = "MyFileListAdapter";

	private SimpleDateFormat timeDateFormat;

	private WifiController wifiController;

	private ClientExceptionRelateHandler exceptionHandler = new ClientExceptionRelateHandler() {

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MessageCode.FILE_FOLDER_RENAME_EXIST:
				Message renameMsg = new Message();
				renameMsg.what = UiConstant.RENAME_FILEFOLDER_ITEM;
				renameMsg.setData(msg.getData());
				renameMsg.obj = msg.obj;
				handlerRefurbish.sendMessage(renameMsg);
				break;
			case MessageCode.FILE_FOLDER_MOVE_EXIST:
				Message moveMsg = new Message();
				moveMsg.what = UiConstant.MOVE_FILE_FOLDER_ITEM;
				moveMsg.obj = msg.obj;
				handlerRefurbish.sendMessage(moveMsg);
				break;
			default:
				super.handleMessage(msg);
				break;
			}
		}

		@Override
		protected void onException_404_NoSuchFolder(Message msg, String errorCode) {
			View itemViw = (View) msg.obj;
			((ShareDriveMainFragmentActivity) context).allFilePage.removeItem(itemViw);
		}

		@Override
		protected void onException_404_NoSuchFile(Message msg, String errorCode) {
			View itemViw = (View) msg.obj;
			((ShareDriveMainFragmentActivity) context).allFilePage.removeItem(itemViw);
		}

		@Override
		protected void onException_404_NoSuchItem(Message msg, String errorCode) {
			View itemViw = (View) msg.obj;
			((ShareDriveMainFragmentActivity) context).allFilePage.removeItem(itemViw);
		}

		@Override
		public Context getContext() {
			return MyFileListAdapter.this.context;
		}
	};

	// custom adapter
	public MyFileListAdapter(Context context, Handler handler, List<FileFolderInfo> fileList, ICloudDriveService cloudDriveService) {
		// Auto-generated constructor stub
		this.context = context;
		this.fileList = fileList;
		this.handlerRefurbish = handler;
		this.cloudDriveService = cloudDriveService;
		mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		initMDMFile();
		File thumBnail = new File(DirectoryUtil.getCurrentThumbnailPath(context));
		if (!thumBnail.exists()) {
			thumBnail.mkdirs();
		}
	}

	@Override
	public int getCount() {
		return fileList.size();
	}

	@Override
	public String getItem(int position) {
		return null;
	}

	@Override
	public long getItemId(int position) {

		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {

		if (null == convertView) {
			convertView = getViewHolder(convertView);
		}
		wifiController = ShareDriveApplication.getInstance().getWifiController();
		ViewHolder holder = (ViewHolder) convertView.getTag();
		final View convertViews = convertView;
		final ViewHolder viewHolder = holder;
		final FileFolderInfo fileFolderInfo = fileList.get(position);
		viewHolder.itemView = convertView;
		viewHolder.fileInformation = fileFolderInfo;
		viewHolder.path = DirectoryUtil.generateFileDownloadPath(context, viewHolder.fileInformation.getOwnerBy(), viewHolder.fileInformation.getId(),
				viewHolder.fileInformation.getName());
		viewHolder.initDownloadTask();
		viewHolder.refreshHandler.sendEmptyMessage(Constant.CLOUD_ADAPTER_HANDLER_INITUI);
		if (fileFolderInfo.getIsFile() == 1) {
			viewHolder.initFileSyncData();
		} else {
			viewHolder.initFolderSyncData();
		}
		viewHolder.pwPopupWindow = new PopupWindow(viewHolder.moreView, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, true);
		viewHolder.pwPopupWindow.setOutsideTouchable(true);
		initOnclickListener(convertViews, viewHolder);
		return convertView;
	}

	private void initOnclickListener(final View conView, final ViewHolder viewHolder) {
		// TODO Auto-generated method stub
		viewHolder.more.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if (cloudDriveService.checkIsRootAndNotify()) {
					return;
				}
				// if (viewHolder.fileInformation.getIsUpload() != 1) {
				int[] loction = new int[2];
				v.getLocationOnScreen(loction);
				int more_img_y = loction[1];
				// viewHolder.more.setBackgroundResource(R.drawable.more_pitch);
				// viewHolder.pwPopupWindow = new
				// PopupWindow(viewHolder.moreView, LayoutParams.MATCH_PARENT,
				// LayoutParams.WRAP_CONTENT, true);
				// PopupWindow pw = viewHolder.pwPopupWindow.initPopupWindow(
				// viewHolder.moreView, LayoutParams.MATCH_PARENT,
				// LayoutParams.WRAP_CONTENT);
				viewHolder.pwPopupWindow.setOnDismissListener(new OnDismissListener() {
					@Override
					public void onDismiss() {
						viewHolder.more_im.setBackgroundResource(R.mipmap.more_nopitch);
						// Toast.makeText(context, "11254",
						// Toast.LENGTH_SHORT).show();
					}
				});
				// pw.showAsDropDown(textView, 0, height);
				// viewHolder.pwPopupWindow.setOutsideTouchable(true);
				viewHolder.pwPopupWindow.setBackgroundDrawable(new BitmapDrawable());
				viewHolder.pwPopupWindow.showAtLocation(conView, Gravity.TOP, 0, more_img_y + (v.getHeight() / 2 + 20));
				viewHolder.more_im.setBackgroundResource(R.mipmap.more_pitch);
				// } else {
				// UploadTask uploadTask =
				// viewHolder.fileInformation.getUploadTask();
				// uploadTask.cancelUploadTask();
				// Intent intent = new Intent(Constant.REFRESH_APPSTORE_ACTION);
				// intent.putExtra("fId",
				// viewHolder.fileInformation.getParent());
				// intent.putExtra("isShowDailog", 1000);
				// context.sendBroadcast(intent);
				// }

			}
		});
		viewHolder.item_img_re.setOnLongClickListener(new View.OnLongClickListener() {

			@Override
			public boolean onLongClick(View arg0) {
				// TODO Auto-generated method stub
				if (ShareDriveApplication.getInstance().isScrolling()) {
					return false;
				} else {
					return true;
				}
			}
		});
		viewHolder.item_img_re.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// check root
				if (cloudDriveService.checkIsRootAndNotify()) {
					return;
				}
				if (!ShareDriveApplication.getInstance().isFastDoubleClick()) {
					// context.send
					if (ShareDriveApplication.getInstance().isScrolling()) {
					} else {
						if (viewHolder.fileInformation.getIsFile() == 0) {
							Message msg = new Message();
							msg.obj = viewHolder.fileInformation;
							msg.what = UiConstant.OPEN_FOLDER_BY_FILEFOLDERINFO;
							handlerRefurbish.sendMessage(msg);
						} else// open file
						{
							if (PublicTools.isFileType(viewHolder.path, Constant.IMAGE_TYPE)) {
								long fileSize = 0;
								File imgFile = new File(viewHolder.path);
								if (imgFile.exists()) {
									fileSize = imgFile.length();
								} else {
									fileSize = viewHolder.fileInformation.getSize();
								}

								if (fileSize > Constant.MAX_ALLOWED_VIEW_PICTURE_SIZE) {
									Toast.makeText(context, context.getString(R.string.picture_too_big), Toast.LENGTH_LONG).show();
									return;
								}
							}

							// if file cached,then open it
							if (viewHolder.isDownload) {
								Toast.makeText(context, context.getString(R.string.fileListadapter_process_download), Toast.LENGTH_SHORT).show();
								return;
							}
							FileInfo fileInfo = null;
							if (null != cloudDriveService) {
								fileInfo = cloudDriveService.selectFile(viewHolder.fileInformation);
							}
							//
							final iFileManager mdmTools = FileManagerFactory.getFileManager(context);
							if (null != fileInfo && (fileInfo.getTransStatus() == Constant.DOWNLOAD_SUCCESS_UPDATE_DB)) {
								if (null != mdmTools) {
									// Open download ui
									if (PublicTools.isFileType(viewHolder.path, Constant.MUSIC_TYPE)) {
										Intent intent = new Intent(context, FileDownloadActivity.class);
										Log.i("liuxiang", viewHolder.fileInformation + "viewHolder.fileInformation");
										intent.putExtra(ClientConfig.FILE_FOLDER_INFO, viewHolder.fileInformation);
										intent.putExtra("isMusic", true);
										context.startActivity(intent);
										((Activity) context).overridePendingTransition(R.anim.right_in, R.anim.left_out);
									} else if (PublicTools.isFileType(viewHolder.path, Constant.IMAGE_TYPE)) {
										Intent intent = new Intent(context, ImageViewActivity.class);
										Log.i("liuxiang", viewHolder.fileInformation + "viewHolder.fileInformation");
										intent.putExtra(ClientConfig.FILE_FOLDER_INFO, viewHolder.fileInformation);
										context.startActivity(intent);
										((Activity) context).overridePendingTransition(R.anim.right_in, R.anim.left_out);
									} else {
										Log.e("~~", "viewHolder.path：" + viewHolder.path);
										mdmTools.openFile(viewHolder.path, viewHolder.fileInformation.getSize());
									}
								}
							} else {
								if (!wifiController.getNetworkState()) {
									Toast.makeText(context, context.getString(R.string.clouddrive_mode_without_internet), Toast.LENGTH_SHORT).show();
								} else {
									if (ClientConfig.NETWORK_ISWIFI.equals(wifiController.getWifiType()) || !PublicTools.getDownloadRemind(context)) {
										Intent intent = null;
										if (PublicTools.isFileType(viewHolder.path, Constant.IMAGE_TYPE)) {
											intent = new Intent(context, ImageViewActivity.class);
										} else {
											intent = new Intent(context, FileDownloadActivity.class);
										}
										intent.putExtra(ClientConfig.FILE_FOLDER_INFO, viewHolder.fileInformation);
										context.startActivity(intent);
										((Activity) context).overridePendingTransition(R.anim.right_in, R.anim.left_out);
									} else {
										final ClouddriveDialog menuDialog = new ClouddriveDialog(context, R.style.myDialogTheme, R.layout.window_wifi_dialog);
										menuDialog.setHeigth(LayoutParams.MATCH_PARENT);
										menuDialog.setWidth(LayoutParams.MATCH_PARENT);
										menuDialog.setCanceledOnTouchOutside(true);
										menuDialog.show();
										View conventView = menuDialog.getConventView();
										Button confirmBt = (Button) conventView.findViewById(R.id.confirm_btn);

										// dialog confirm
										confirmBt.setOnClickListener(new OnClickListener() {
											@Override
											public void onClick(View v) {
												// TODO Auto-generated
												menuDialog.dismiss();
												Intent intent = null;
												if (PublicTools.isFileType(viewHolder.path, Constant.IMAGE_TYPE)) {
													intent = new Intent(context, ImageViewActivity.class);
												} else {
													intent = new Intent(context, FileDownloadActivity.class);
												}
												// FileInfo fileInfomation =
												// DAOFactory.instance(context).getFileDao()
												// .getFileById(viewHolder.fileInformation.getId());
												intent.putExtra(ClientConfig.FILE_FOLDER_INFO, viewHolder.fileInformation);
												context.startActivity(intent);
												((Activity) context).overridePendingTransition(R.anim.right_in, R.anim.left_out);
											}
										});
										Button cancleBt = (Button) conventView.findViewById(R.id.cancle_btn);
										cancleBt.setOnClickListener(new OnClickListener() {
											@Override
											public void onClick(View v) {
												// TODO Auto-generated method
												// stub
												menuDialog.dismiss();
											}
										});

									}
								}
							}
						}
					}
				}
			}
		});

		// download click event
		viewHolder.window_more_collect_ll.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// root check
				if (cloudDriveService.checkIsRootAndNotify()) {
					return;
				}
				// downloading
				if (null != viewHolder.pwPopupWindow && viewHolder.pwPopupWindow.isShowing()) {
					viewHolder.pwPopupWindow.dismiss();
				}
				if (!wifiController.getNetworkState()) {
					Toast.makeText(context, context.getString(R.string.clouddrive_mode_without_internet), Toast.LENGTH_SHORT).show();
				} else {
					// if folder,then sync
					if (viewHolder.fileInformation.getIsFile() == 0) {
						FolderInfo folderInfo = new FolderInfo();
						// query if local cache
						if (null != cloudDriveService)
							folderInfo = cloudDriveService.selectFolder(viewHolder.fileInformation);
						//
						if (null != folderInfo) {
							// if not local cache, or need cache,then cache to
							// local
							if ((!folderInfo.isSync()) || viewHolder.needUpdateFromServer) {
								if (ClientConfig.NETWORK_ISWIFI.equals(wifiController.getWifiType()) || !PublicTools.getDownloadRemind(context)) {
									viewHolder.checkAuthAndSyncFolder();
								} else {
									final ClouddriveDialog menuDialog = new ClouddriveDialog(context, R.style.myDialogTheme, R.layout.window_wifi_dialog);
									menuDialog.setHeigth(LayoutParams.MATCH_PARENT);
									menuDialog.setWidth(LayoutParams.MATCH_PARENT);
									menuDialog.setCanceledOnTouchOutside(true);
									menuDialog.show();
									View conventView = menuDialog.getConventView();
									Button confirmBt = (Button) conventView.findViewById(R.id.confirm_btn);
									CheckBox cb = (CheckBox) conventView.findViewById(R.id.cloud_wifi_cb);
									cb.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener() {

										@Override
										public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
											// TODO Auto-generated
											// method
											// stub
											Toast.makeText(context, "" + arg1, Toast.LENGTH_SHORT).show();
											PublicTools.setDownloadRemind(context, !arg1);
										}
									});
									confirmBt.setOnClickListener(new OnClickListener() {
										@Override
										public void onClick(View v) {
											// TODO
											// Auto-generated
											// method stub
											menuDialog.dismiss();

											// local cache(true:cache,false:no
											// cache)
											Message message1 = new Message();
											message1.what = UiConstant.INIT_VIEW_DOWNLOAD_STATE;
											viewHolder.downloadHandler.sendMessage(message1);
											if (null != cloudDriveService) {
												// local cache(1:cache,0:don't
												// cache)
												viewHolder.checkAuthAndSyncFolder();
											}

											viewHolder.needUpdateFromServer = false;
											// refresh progress
											new Thread(new Runnable() {
												@Override
												public void run() {
													// mark local cache
													for (int i = 0; i <= 100; i++) {
														Message message = new Message();
														message.what = UiConstant.FOLDER_IS_DOWNLOADDING;
														message.arg1 = 0;
														message.arg2 = i;
														viewHolder.downloadHandler.sendMessage(message);
														try {
															Thread.sleep(40);
														} catch (InterruptedException e) {
															// Auto-generated
															// catch
															// block
															e.printStackTrace();
														}
													}
												}
											}).start();
										}
									});
									Button cancleBt = (Button) conventView.findViewById(R.id.cancle_btn);
									cancleBt.setOnClickListener(new OnClickListener() {
										@Override
										public void onClick(View v) {
											// TODO Auto-generated
											// method
											// stub
											menuDialog.dismiss();
										}
									});
								}

							} else {
								// local cache operation(1:cache,0:don't cache)
								if (null != cloudDriveService) {
									cloudDriveService.updateFileSyncStatus(0, viewHolder.fileInformation);
								}
								Message message = new Message();
								message.what = UiConstant.CANCEL_SYNC_FILE;
								viewHolder.downloadHandler.sendMessage(message);
								// cancel local cache(true:cache,false:don't
								// cache)
								if (null != cloudDriveService) {
									cloudDriveService.cancelSyncFolder(viewHolder.fileInformation.getOwnerId(), viewHolder.fileInformation.getId(),
											viewHolder.fileInformation.getName());
								}
							}
						}

					} else {
						if (!viewHolder.isDownload) {
							FileInfo fileInfo = new FileInfo();
							if (null != cloudDriveService)
								fileInfo = cloudDriveService.selectFile(viewHolder.fileInformation);

							final iFileManager mdmTools = FileManagerFactory.getFileManager(context);

							if (null != fileInfo) {
								if (fileInfo.getTransStatus() == Constant.DOWNLOAD_SUCCESS_UPDATE_DB) {
									if (fileInfo.isSync()) {
										// change cache status
										if (null != cloudDriveService) {
											cloudDriveService.updateFileSyncStatus(Constant.DOWNLOAD_STATUS_NOCACHE_DB, viewHolder.fileInformation);
											cloudDriveService.updateTransStatus(viewHolder.fileInformation, Constant.DOWNLOAD_NON_UPDATE_DB);
										}
										iFileManager mdm = FileManagerFactory.getFileManager(context);
										mdm.deleteFile(viewHolder.path);
										viewHolder.pinProgressButton.setVisibility(View.GONE);
										viewHolder.item_pin_progress_above_im.setVisibility(View.GONE);
										viewHolder.window_more_collect_im.setBackgroundResource(R.mipmap.more_setting_synchronization);
										viewHolder.window_more_collect_tv.setText(context.getString(R.string.fileListadapter_keep));
									} else {
										// if has download,then mark as
										// download,don't need download
										if (null != cloudDriveService)
											cloudDriveService.updateFileSyncStatus(Constant.DOWNLOAD_STATUS_CACHE_DB, viewHolder.fileInformation);
										Message message = new Message();
										message.what = UiConstant.INIT_VIEW_DOWNLOAD_STATE;
										viewHolder.downloadHandler.sendMessage(message);
									}
								} else {
									if (!wifiController.getNetworkState()) {
										Toast.makeText(context, context.getString(R.string.clouddrive_mode_without_internet), Toast.LENGTH_SHORT).show();
									} else {
										if (ClientConfig.NETWORK_ISWIFI.equals(wifiController.getWifiType()) || !PublicTools.getDownloadRemind(context)) {
											viewHolder.checkAuthAndDownloadFile(mdmTools);
										} else {
											final ClouddriveDialog menuDialog = new ClouddriveDialog(context, R.style.myDialogTheme,
													R.layout.window_wifi_dialog);
											menuDialog.setHeigth(LayoutParams.MATCH_PARENT);
											menuDialog.setWidth(LayoutParams.MATCH_PARENT);
											menuDialog.setCanceledOnTouchOutside(true);
											menuDialog.show();
											View conventView = menuDialog.getConventView();
											Button confirmBt = (Button) conventView.findViewById(R.id.confirm_btn);
											CheckBox cb = (CheckBox) conventView.findViewById(R.id.cloud_wifi_cb);
											cb.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener() {
												@Override
												public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
													// TODO
													// Auto-generated
													// method
													// stub
													Toast.makeText(context, "" + arg1, Toast.LENGTH_SHORT).show();
													PublicTools.setDownloadRemind(context, !arg1);
												}
											});
											confirmBt.setOnClickListener(new OnClickListener() {
												@Override
												public void onClick(View v) {
													menuDialog.dismiss();
													viewHolder.checkAuthAndDownloadFile(mdmTools);
												}
											});
											Button cancleBt = (Button) conventView.findViewById(R.id.cancle_btn);
											cancleBt.setOnClickListener(new OnClickListener() {
												@Override
												public void onClick(View v) {
													// TODO
													// Auto-generated
													// method
													// stub
													menuDialog.dismiss();
												}
											});
										}
									}
								}
							}
						} else {
							// cancel download
							DownloadTask task = null;
							if (null != cloudDriveService) {
								task = cloudDriveService.getDownloadTask(viewHolder.fileInformation.getId());
							}
							if (null != task) {
								try {
									task.cancelDownloadTask();
								} catch (Exception e) {
									LogUtil.e(LOG_TAG, "Cancel Download Fail...");
								}
							}
							viewHolder.downloadHandler.sendEmptyMessage(UiConstant.REQUEST_CANCEL_DOWNLOAD);
						}
					}

				}

			}

		});
		// delete operation
		viewHolder.window_more_delete_ll.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// root check
				if (cloudDriveService.checkIsRootAndNotify()) {
					return;
				}
				if (!viewHolder.isDownload) {
					if (null != viewHolder.pwPopupWindow && viewHolder.pwPopupWindow.isShowing()) {
						viewHolder.pwPopupWindow.dismiss();
					}
					if (!wifiController.getNetworkState()) {
						Toast.makeText(context, context.getString(R.string.clouddrive_mode_without_internet), Toast.LENGTH_SHORT).show();
					} else {
						Bundle bundle = new Bundle();
						bundle.putSerializable("delete", viewHolder.fileInformation);
						Message msg = new Message();
						msg.what = UiConstant.DELETE_FILEFOLDER_ITEM;
						msg.obj = conView;
						msg.setData(bundle);
						handlerRefurbish.sendMessage(msg);
					}
				} else {
					Toast.makeText(context, context.getString(R.string.fileListadapter_process_download), Toast.LENGTH_SHORT).show();
				}
			}
		});
		// publish link
		viewHolder.window_more_link_ll.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// root check
				if (cloudDriveService.checkIsRootAndNotify()) {
					return;
				}
				if (!viewHolder.isDownload) {
					if (null != viewHolder.pwPopupWindow && viewHolder.pwPopupWindow.isShowing()) {
						viewHolder.pwPopupWindow.dismiss();
					}
					if (!wifiController.getNetworkState()) {
						Toast.makeText(context, context.getString(R.string.clouddrive_mode_without_internet), Toast.LENGTH_SHORT).show();
					} else {
						Bundle bundle = new Bundle();
						bundle.putSerializable("link", viewHolder.fileInformation);
						Message msg = new Message();
						msg.what = UiConstant.SET_SHARE_LINK;
						msg.obj = conView;
						msg.setData(bundle);
						handlerRefurbish.sendMessage(msg);
					}
				} else {
					Toast.makeText(context, context.getString(R.string.fileListadapter_process_download), Toast.LENGTH_SHORT).show();
				}

			}
		});
		// rename done
		viewHolder.window_more_rename_ll.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// root check
				if (cloudDriveService.checkIsRootAndNotify()) {
					return;
				}
				if (!viewHolder.isDownload) {
					if (null != viewHolder.pwPopupWindow && viewHolder.pwPopupWindow.isShowing()) {
						viewHolder.pwPopupWindow.dismiss();
					}
					if (!wifiController.getNetworkState()) {
						Toast.makeText(context, context.getString(R.string.clouddrive_mode_without_internet), Toast.LENGTH_SHORT).show();
					} else {
						new Thread(new Runnable() {
							public void run() {
								boolean result = new MoveAction(context).checkFileFolderExist(cloudDriveService, viewHolder.fileInformation, conView,
										exceptionHandler);
								if (result) {
									Bundle bundle = new Bundle();
									bundle.putSerializable("rename", viewHolder.fileInformation);
									Message msg = new Message();
									msg.what = MessageCode.FILE_FOLDER_RENAME_EXIST;
									msg.obj = conView;
									msg.setData(bundle);
									exceptionHandler.sendMessage(msg);
								}
							}
						}).start();
					}
				} else {
					Toast.makeText(context, context.getString(R.string.fileListadapter_process_download), Toast.LENGTH_SHORT).show();
				}

			}
		});
		// file/folder move
		viewHolder.window_more_move_ll.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if (!viewHolder.isDownload) {
					if (null != viewHolder.pwPopupWindow && viewHolder.pwPopupWindow.isShowing()) {
						viewHolder.pwPopupWindow.dismiss();
					}
					if (!wifiController.getNetworkState()) {
						Toast.makeText(context, context.getString(R.string.clouddrive_mode_without_internet), Toast.LENGTH_SHORT).show();
					} else {
						new Thread(new Runnable() {
							public void run() {
								boolean result = new MoveAction(context).checkFileFolderExist(cloudDriveService, viewHolder.fileInformation, conView,
										exceptionHandler);
								if (result) {
									Message msg = new Message();
									msg.what = MessageCode.FILE_FOLDER_MOVE_EXIST;
									msg.obj = viewHolder.fileInformation;
									exceptionHandler.sendMessage(msg);
								}
							}
						}).start();
					}
				} else {
					Toast.makeText(context, context.getString(R.string.fileListadapter_process_download), Toast.LENGTH_SHORT).show();
				}
			}
		});
		// share operation
		viewHolder.window_more_share_ll.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if (null != viewHolder.pwPopupWindow && viewHolder.pwPopupWindow.isShowing()) {
					viewHolder.pwPopupWindow.dismiss();
				}
				if (!wifiController.getNetworkState()) {
					Toast.makeText(context, context.getString(R.string.clouddrive_mode_without_internet), Toast.LENGTH_SHORT).show();
				} else {
					// root check
					if (cloudDriveService.checkIsRootAndNotify()) {
						return;
					}
					if (!viewHolder.isDownload) {
						new GetShareUserAsyncTask(viewHolder.fileInformation, viewHolder.ahandler).execute();
					} else {
						Toast.makeText(context, context.getString(R.string.fileListadapter_process_download), Toast.LENGTH_SHORT).show();
					}
				}
			}
		});
	}

	private View getViewHolder(View convertView) {
		// TODO Auto-generated method stub
		ViewHolder holder = new ViewHolder();
		convertView = mInflater.inflate(R.layout.item_filelist, null);

		holder.fileName = (TextView) convertView.findViewById(R.id.item_name_text);
		holder.date = (TextView) convertView.findViewById(R.id.item_date_text);
		holder.more = (RelativeLayout) convertView.findViewById(R.id.item_more_ll);
		holder.typeImg = (ImageView) convertView.findViewById(R.id.item_type_img);
		holder.more_im = (ImageView) convertView.findViewById(R.id.item_more_img);
		holder.fileSize = (TextView) convertView.findViewById(R.id.item_filelist_file_size);
		holder.pinProgressButton = (PinProgressButton) convertView.findViewById(R.id.item_pin_progress);
		holder.item_pin_progress_above_im = (ImageView) convertView.findViewById(R.id.item_pin_progress_above_im);
		holder.item_progress_horizontal = (ProgressBar) convertView.findViewById(R.id.item_progress_horizontal);
		holder.item_img_re = (RelativeLayout) convertView.findViewById(R.id.item_img_re);
		holder.item_filestateupdate_img = (ImageView) convertView.findViewById(R.id.item_filestateupdate_img);
		holder.moreView = mInflater.inflate(R.layout.window_more, null);
		holder.window_more_collect_ll = (LinearLayout) holder.moreView.findViewById(R.id.window_more_collect_ll);
		holder.window_more_move_ll = (LinearLayout) holder.moreView.findViewById(R.id.window_more_move_ll);
		holder.window_more_share_ll = (LinearLayout) holder.moreView.findViewById(R.id.window_more_share_ll);
		holder.window_more_delete_ll = (LinearLayout) holder.moreView.findViewById(R.id.window_more_delete_ll);
		holder.window_more_rename_ll = (LinearLayout) holder.moreView.findViewById(R.id.window_more_rename_ll);
		holder.window_more_link_ll = (LinearLayout) holder.moreView.findViewById(R.id.window_more_link_ll);
		holder.window_more_collect_im = (ImageView) holder.moreView.findViewById(R.id.window_more_collect_im);
		holder.window_more_collect_tv = (TextView) holder.moreView.findViewById(R.id.window_more_collect_tv);
		convertView.setTag(holder);
		return convertView;
	}

	public class ViewHolder {

		public TextView fileName;

		public TextView date;

		private ImageView typeImg;

		private RelativeLayout more;

		private TextView fileSize;

		private ImageView more_im;

		private PinProgressButton pinProgressButton;

		private ImageView item_pin_progress_above_im;

		private ProgressBar item_progress_horizontal;

		private RelativeLayout item_img_re;

		// private String parentID;
		private View moreView;

		private LinearLayout window_more_collect_ll;

		private LinearLayout window_more_move_ll;

		private LinearLayout window_more_share_ll;

		private LinearLayout window_more_delete_ll;

		private LinearLayout window_more_rename_ll;

		private LinearLayout window_more_link_ll;

		private ImageView window_more_collect_im;

		private TextView window_more_collect_tv;

		private ClouddriveDialog dialog;

		private ImageView item_filestateupdate_img;

		private boolean needUpdateFromServer;

		private DownloadTask downloadTask = null;

		// private String fileID = null;
		public FileFolderInfo fileInformation;

		private String fileIconPath;

		public String path;

		private boolean isDownload;

		private View itemView;

		private PopupWindow pwPopupWindow;

		public ImageView getItem_filestateupdate_img() {
			return item_filestateupdate_img;
		}

		// download handler
		private Handler downloadHandler = new Handler() {
			public void handleMessage(Message msg) {
				// download file
				switch (msg.what) {
				case UiConstant.FOLDER_IS_DOWNLOADDING:
					handleFolderIsDownloadding(msg);
					break;

				case UiConstant.FILE_IS_DOWNLOADDING:
					handleFileIsDownloadding(msg);
					break;

				case UiConstant.FILE_DOWNLOAD_CANCEL:
					handleCancelDownloadding(msg);
					break;

				case UiConstant.REQUEST_CANCEL_DOWNLOAD:
					handleCancelFileDownloadding();
					break;

				case UiConstant.FILE_DOWNLOAD_SUCCESS:
					LogUtil.i(TAG, "Download File Success...");
					handleDownloadSuccess();
					break;

				case UiConstant.INIT_VIEW_DOWNLOAD_STATE:// local cache
					handleSyncOperation();
					break;

				case UiConstant.CANCEL_SYNC_FILE:// cancel local cache
					handleCancelSyncOperation();
					break;

				case UiConstant.CURRENT_ITEM_VIEW_NEED_UPLOAD:// change status
																// to cache
					handleFileNeedUpdate();
					break;

				case UiConstant.GET_FOLDER_SUB_COLLECTION_FAILED:// task
																	// download,exception
																	// appear
					pinProgressButton.setVisibility(View.GONE);
					item_pin_progress_above_im.setVisibility(View.GONE);
					window_more_collect_tv.setText(context.getString(R.string.fileListadapter_keep));
					if (null != dialog) {
						dialog.dismiss();
					}
					isDownload = false;
					window_more_collect_ll.setClickable(true);
					item_img_re.setClickable(true);
					Toast.makeText(context, context.getString(R.string.fileListadapter_keep_failed), Toast.LENGTH_SHORT).show();

					Message uploadMsg = new Message();
					Bundle uploadBundle = new Bundle();
					uploadBundle.putString("folderID", msg.obj.toString());
					uploadMsg.setData(uploadBundle);
					uploadMsg.what = UiConstant.GET_FILE_FOLDER_LIST;
					uploadMsg.arg1 = 0;
					handlerRefurbish.sendMessage(uploadMsg);

					downloadHandler.sendEmptyMessage(UiConstant.CURRENT_ITEM_VIEW_NEED_UPLOAD);
					break;

				case UiConstant.CURRENT_ITEM_RESOURCE_NOT_EXITST:
					handleResourceIsNotExitst();

					Message downResNotExistMsg = new Message();
					downResNotExistMsg.what = AllFileFragment.resourceIsNotExist;
					downResNotExistMsg.obj = itemView;
					downResNotExistMsg.arg1 = AllFileFragment.sendFromDownload;
					handlerRefurbish.sendMessage(downResNotExistMsg);
					break;

				case UiConstant.THUMBNAIL_DOWNLOAD_SUCCESS:// decodeBitmapfile
					new Thread(new Runnable() {
						@Override
						public void run() {
							Bitmap bmp = BitmapFactory.decodeFile(fileIconPath);
							ShareDriveApplication.getInstance().addCloudBitmaps(bmp);
							Message message = new Message();
							message.what = UiConstant.UPDATE_TYPE_ICON;
							message.obj = bmp;
							downloadHandler.sendMessage(message);
						}
					}).start();
					break;

				case UiConstant.UPDATE_TYPE_ICON:// refresh image ui
					Bitmap bmp = (Bitmap) msg.obj;
					if (null != bmp)
						typeImg.setImageBitmap(bmp);
					else {
						LogUtil.e(LOG_TAG, "bitmap is null, show default img..." + " | fileIconPath:" + fileIconPath);
					}
					break;

				case UiConstant.SHOW_BEGIN_DOWNLOAD_TYPE_ICON:
					handleBeginDownload();
					break;

				case Constant.DOWNLOAD_FAIL_FILE_LARGERTHAN_CACHESIZE:
					Toast.makeText(context, context.getResources().getString(R.string.download_file_larger_than_local_cache), Toast.LENGTH_SHORT).show();
					break;
				}
			}

			private void handleResourceIsNotExitst() {
				pinProgressButton.setVisibility(View.GONE);
				item_pin_progress_above_im.setVisibility(View.GONE);
				window_more_collect_tv.setText(context.getString(R.string.fileListadapter_keep));
				if (null != dialog) {
					dialog.dismiss();
				}
				isDownload = false;
				window_more_collect_ll.setClickable(true);
				item_img_re.setClickable(true);
				// Toast.makeText(context,
				// context.getString(R.string.fileListadapter_file_notfond),
				// Toast.LENGTH_SHORT).show();
			}

			private void handleFileNeedUpdate() {
				pinProgressButton.setVisibility(View.GONE);
				item_pin_progress_above_im.setVisibility(View.GONE);

				int state = DAOFactory.instance(context).getFileDao().getTransStatus(fileInformation);
				if (fileInformation.getIsFile() != Constant.FOLDER && state == Constant.DOWNLOAD_CANCEL_UPDATE_DB) {
					window_more_collect_tv.setText(context.getString(R.string.fileListadapter_keep));
					window_more_collect_im.setBackgroundResource(R.mipmap.more_setting_synchronization);
					item_filestateupdate_img.setVisibility(View.GONE);
				} else {
					window_more_collect_tv.setText(context.getString(R.string.fileListadapter_immediately_synchronization));
					window_more_collect_im.setBackgroundResource(R.mipmap.more_synchronization);
					item_filestateupdate_img.setVisibility(View.VISIBLE);
				}
			}

			private void handleCancelSyncOperation() {
				pinProgressButton.setVisibility(View.GONE);
				item_pin_progress_above_im.setVisibility(View.GONE);
				item_filestateupdate_img.setVisibility(View.GONE);
				window_more_collect_tv.setText(context.getString(R.string.fileListadapter_keep));
				window_more_collect_im.setBackgroundResource(R.mipmap.more_setting_synchronization);
			}

			private void handleSyncOperation() {
				pinProgressButton.setVisibility(View.VISIBLE);
				item_pin_progress_above_im.setVisibility(View.VISIBLE);
				pinProgressButton.setMax(100);
				pinProgressButton.setProgress(100);
				updatePinProgressContentDescription(pinProgressButton);
				window_more_collect_tv.setText(context.getString(R.string.fileListadapter_cancel_keep));
				window_more_collect_im.setBackgroundResource(R.mipmap.more_cancelsynchronization);
			}

			private void handleDownloadSuccess() {
				Toast.makeText(context, context.getString(R.string.fileListadapter_keep_success), Toast.LENGTH_SHORT).show();
				pinProgressButton.setVisibility(View.VISIBLE);
				item_pin_progress_above_im.setVisibility(View.VISIBLE);
				pinProgressButton.setMax(100);
				pinProgressButton.setProgress(100);
				window_more_collect_tv.setText(context.getString(R.string.fileListadapter_cancel_keep));
				isDownload = false;
				window_more_collect_ll.setClickable(true);
				item_img_re.setClickable(true);
			}

			private void handleCancelFileDownloadding() {
				item_filestateupdate_img.setVisibility(View.GONE);
				pinProgressButton.setVisibility(View.GONE);
				item_pin_progress_above_im.setVisibility(View.GONE);
				window_more_collect_tv.setText(context.getString(R.string.fileListadapter_keep));
				if (null != dialog) {
					dialog.dismiss();
				}
				isDownload = false;
				window_more_collect_im.setBackgroundResource(R.mipmap.more_setting_synchronization);
				window_more_collect_ll.setClickable(true);
				item_img_re.setClickable(true);
			}

			private void handleCancelDownloadding(Message msg) {
				item_filestateupdate_img.setVisibility(View.GONE);
				pinProgressButton.setVisibility(View.GONE);
				item_pin_progress_above_im.setVisibility(View.GONE);
				window_more_collect_tv.setText(context.getString(R.string.fileListadapter_keep));
				window_more_collect_im.setBackgroundResource(R.mipmap.more_setting_synchronization);
				if (null != dialog) {
					dialog.dismiss();
				}
				isDownload = false;
				window_more_collect_ll.setClickable(true);
				item_img_re.setClickable(true);
				if (1 == msg.arg1) {
					Toast.makeText(context, context.getString(R.string.fileListadapter_keep_failed), Toast.LENGTH_SHORT).show();
				} else if (2 == msg.arg1) {
					// cancel success
					Toast.makeText(context, context.getString(R.string.fileListadapter_cancel_keep), Toast.LENGTH_SHORT).show();
					fileSize.setText(PublicTools.changeBKM(String.valueOf(fileInformation.getSize())));
				}
			}

			private void handleFileIsDownloadding(Message msg) {
				if (msg.arg1 == 100 && msg.arg2 > -1) {
					pinProgressButton.setMax(msg.arg1);
					pinProgressButton.setProgress(msg.arg2);
					updatePinProgressContentDescription(pinProgressButton);
					pinProgressButton.setVisibility(View.VISIBLE);
					item_pin_progress_above_im.setVisibility(View.VISIBLE);
					window_more_collect_tv.setText(context.getString(R.string.fileListadapter_course_keep));
					window_more_collect_im.setBackgroundResource(R.mipmap.more_cancelsynchronization);
					isDownload = true;
					window_more_collect_tv.setText(R.string.fileListadapter_cancel_keep);
					item_img_re.setClickable(false);
					item_filestateupdate_img.setVisibility(View.GONE);
					if (null != (String) msg.obj) {
						fileSize.setText((String) msg.obj);
					} else {
						fileSize.setText(PublicTools.changeBKM(String.valueOf(fileInformation.getSize())));
					}
				}
			}

			private void handleBeginDownload() {
				window_more_collect_ll.setClickable(false);
				window_more_collect_tv.setText(context.getString(R.string.fileListadapter_course_keep));
				window_more_collect_im.setBackgroundResource(R.mipmap.more_synchronization);
			}

			private void handleFolderIsDownloadding(Message msg) {
				pinProgressButton.setVisibility(View.VISIBLE);
				item_pin_progress_above_im.setVisibility(View.VISIBLE);
				pinProgressButton.setMax(100);
				pinProgressButton.setProgress(msg.arg2);
				updatePinProgressContentDescription(pinProgressButton);
				item_filestateupdate_img.setVisibility(View.GONE);
				if (msg.arg2 == 100) {
					window_more_collect_tv.setText(R.string.fileListadapter_cancel_keep);
					window_more_collect_ll.setClickable(true);
					window_more_collect_im.setBackgroundResource(R.mipmap.more_cancelsynchronization);
				}
			};
		};

		// Download Callback
		private IDownloadCallback downloadCallback = new IDownloadCallback() {
			@Override
			public void onSuccess() {
				// TODO Auto-generated method stub
				// Notify UI : download finish
				Message msg_download = new Message();
				msg_download.what = UiConstant.FILE_DOWNLOAD_SUCCESS;
				msg_download.arg2 = 100; // download
				msg_download.arg1 = 100;// progress max value
				downloadHandler.sendMessage(msg_download);
			}

			@Override
			public void onStart() {
				// TODO Auto-generated method stub
				Message msg = new Message();
				msg.what = UiConstant.FILE_IS_DOWNLOADDING;
				msg.arg1 = 100;// progress max value
				msg.arg2 = 0; // download progress
				downloadHandler.sendMessage(msg);
			}

			@Override
			public void onProgress(int currentProgress, long currentSize, long maxSize) {
				// TODO Auto-generated method stub
				// Notify UI :download progress
				Message msg_download = new Message();
				msg_download.what = UiConstant.FILE_IS_DOWNLOADDING; // download
				msg_download.arg1 = 100;// download progress max value
				msg_download.arg2 = currentProgress;
				String size = "";
				if (100 != currentProgress) {
					long tempMax = currentSize / currentProgress;
					size = PublicTools.changeBKM(String.valueOf(currentSize)) + " / " + PublicTools.changeBKM(String.valueOf(tempMax));
				} else {
					size = PublicTools.changeBKM(String.valueOf(currentSize));
				}
				msg_download.obj = size;
				downloadHandler.sendMessage(msg_download);
			}

			@Override
			public void onFailure(Throwable t, int statusCode) {
				if (statusCode == 401) {
					LogUtil.e(TAG, "download fail [401], need get token...");
					needUpdateFromServer = true;
					downloadHandler.sendEmptyMessage(UiConstant.CURRENT_ITEM_VIEW_NEED_UPLOAD);
				} else if (statusCode == 404) {
					Message msg_download = new Message();
					msg_download.what = UiConstant.CURRENT_ITEM_RESOURCE_NOT_EXITST;
					downloadHandler.sendMessage(msg_download);
				} else if (statusCode == Constant.DOWNLOAD_FAIL_FILE_LARGERTHAN_CACHESIZE) {
					Message msg_download = new Message();
					msg_download.obj = t.getMessage();
					msg_download.what = Constant.DOWNLOAD_FAIL_FILE_LARGERTHAN_CACHESIZE;
					downloadHandler.sendMessage(msg_download);
					needUpdateFromServer = true;
					downloadHandler.sendEmptyMessage(UiConstant.CURRENT_ITEM_VIEW_NEED_UPLOAD);
				} else {
					Message msg_download = new Message();
					if (!"cancel cache success!".equalsIgnoreCase(t.getMessage())) {// cancel
																					// result
						msg_download.arg1 = 1;// download fail
					} else {
						msg_download.arg1 = 2;// cancel success
					}
					msg_download.what = UiConstant.FILE_DOWNLOAD_CANCEL; // download
					downloadHandler.sendMessage(msg_download);
					LogUtil.e(LOG_TAG, "File download final" + " | Message:" + t.getMessage() + " | LocalizedMessage:" + t.getLocalizedMessage());
				}
			}

			@Override
			public void onStop() {
			}

			@Override
			public void onCanceled() {
			}

			@Override
			public void onDettach() {
			}
		};

		private IDownloadThumbnailCallback downloadThumbnailCallback = new IDownloadThumbnailCallback() {
			@Override
			public void onSuccess(String fileId) {
				// TODO Auto-generated method stub
				Message msg_download = new Message();
				msg_download.what = UiConstant.THUMBNAIL_DOWNLOAD_SUCCESS;
				downloadHandler.sendMessage(msg_download);
			}

			@Override
			public void onStart() {
				// TODO Auto-generated method stub
			}

			@Override
			public void onProgress(int currentProgress, long currentSize, long maxSize) {
				// TODO Auto-generated method stub
			}

			@Override
			public void onFailure(Throwable t) {
				// TODO Auto-generated method stub

			}
		};

		private void updatePinProgressContentDescription(PinProgressButton button) {
			// int progress = button.getProgress();
			// if (progress <= 0)
			// {
			// button.setContentDescription(context.getString(button.isChecked()
			// ? R.string.content_desc_pinned_not_downloaded
			// : R.string.content_desc_unpinned_not_downloaded));
			// }
			// else if (progress >= 100)
			// {
			// button.setContentDescription(context.getString(button.isChecked()
			// ? R.string.content_desc_pinned_downloaded
			// : R.string.content_desc_unpinned_downloaded));
			// }
			// else
			// {
			// button.setContentDescription(context.getString(button.isChecked()
			// ? R.string.content_desc_pinned_downloading
			// : R.string.content_desc_unpinned_downloading));
			// }
		}

		public void downloadFile(final iFileManager mdmTools) {
			// TODO
			// Auto-generated
			// method stub
			Message msg = new Message();
			msg.what = UiConstant.FILE_IS_DOWNLOADDING;
			msg.arg1 = 100;// download progress max value
			msg.arg2 = 1; // download progress
			msg.obj = PublicTools.changeBKM(Long.toString(fileInformation.getSize()));
			downloadHandler.sendMessage(msg);
			boolean isDownload = true;
			if (null != cloudDriveService)
				isDownload = cloudDriveService.downloadFile(ShareDriveApplication.getInstance().getWnerID(), fileInformation.getParent(),
						fileInformation.getId(), ShareDriveApplication.getInstance().getAuthorization(), fileInformation.getSize(), path, downloadCallback,
						fileInformation);
			if (!isDownload) {
				Message msg_download = new Message();
				msg_download.what = UiConstant.FILE_DOWNLOAD_CANCEL; // download
				downloadHandler.sendMessage(msg_download);
			}
		}

		void checkAuthAndDownloadFile(final iFileManager mdmTools) {
			DAOFactory.instance(context).getFileDao().updateSyncStatus(fileInformation, Constant.DOWNLOAD_STATUS_CACHE_DB);
			long currentMills = System.currentTimeMillis();
			long time = PublicTools.getExpiredAt(context);
			if (time - currentMills <= 3 * 1000) {
				downloadFileOrLogin(mdmTools);
			} else {
				if (null == ShareDriveApplication.getInstance().getAuthorization()) {
					LogUtil.e(MyFileListAdapter.LOG_TAG, " authorization == null Need relogin");
					ShareDriveApplication.getInstance().setWnerID(PublicTools.getOwnerId(context));
					ShareDriveApplication.getInstance().setAuthorization(PublicTools.getAuthorization(context));
					SharedPreferences settings1 = context.getSharedPreferences(ClientConfig.settings, Context.MODE_APPEND);
					CommonClient.getInstance().setServiceURL(settings1.getString(ClientConfig.SERVER_ADDRESS, ""));
				}
				downloadFile(mdmTools);
			}
		}

		void checkAuthAndSyncFolder() {
			long currentMills = System.currentTimeMillis();
			long time = PublicTools.getExpiredAt(context);
			if (time - currentMills <= 3 * 1000) {
				syncFileOrLogin();
			} else {
				if (null == ShareDriveApplication.getInstance().getAuthorization()) {
					LogUtil.e(MyFileListAdapter.LOG_TAG, " authorization == null Need relogin");
					ShareDriveApplication.getInstance().setWnerID(PublicTools.getOwnerId(context));
					ShareDriveApplication.getInstance().setAuthorization(PublicTools.getAuthorization(context));
					SharedPreferences settings = context.getSharedPreferences(ClientConfig.settings, Context.MODE_APPEND);
					CommonClient.getInstance().setServiceURL(settings.getString(ClientConfig.SERVER_ADDRESS, ""));
				}
				syncFile();
			}
		}

		public void syncFile() {
			// set local cache(true:cache,false:don't cache)
			if (!wifiController.getNetworkState()) {
				Toast.makeText(context, context.getString(R.string.clouddrive_mode_without_internet), Toast.LENGTH_SHORT).show();
				return;
			}
			Message message1 = new Message();
			message1.what = UiConstant.SHOW_BEGIN_DOWNLOAD_TYPE_ICON;
			downloadHandler.sendMessage(message1);
			if (null != cloudDriveService) {
				// local cache(1:cache,0:don't cache)
				cloudDriveService.updateFolderSyncStatus(1, fileInformation);// .updateFileSyncStatus(1,
																				// fileInformation.getId());
				cloudDriveService.syncFolder(fileInformation, fileInformation.getName(), fileInformation.getParent(), exceptionHandler, itemView);
			}
			needUpdateFromServer = false;
			new Thread(new Runnable() {
				@Override
				public void run() {
					// mark as local cache
					// set local database :isSync
					for (int i = 0; i <= 100; i++) {
						Message message = new Message();
						message.what = UiConstant.FOLDER_IS_DOWNLOADDING;
						message.arg1 = 0;
						message.arg2 = i;
						downloadHandler.sendMessage(message);
						try {
							Thread.sleep(40);
						} catch (InterruptedException e) {
							// Auto-generated
							// catch
							// block
							e.printStackTrace();
						}
					}
				}
			}).start();
		}

		public void syncFileOrLogin() {
			new Thread(new Runnable() {
				@Override
				public void run() {
					// TODO Auto-generated method stub
					Actions actions = new Actions(context);
					if (null != cloudDriveService)
						try {
							actions.smartUpdateAuthiorzation();
							// set local cache(true:cache,false:don't cache)
							Message message1 = new Message();
							message1.what = UiConstant.SHOW_BEGIN_DOWNLOAD_TYPE_ICON;
							downloadHandler.sendMessage(message1);
							if (null != cloudDriveService) {
								// local cache(1:cache,0:don't cache)
								cloudDriveService.updateFolderSyncStatus(1, fileInformation);// .updateFileSyncStatus(1,
																								// fileInformation.getId());
								cloudDriveService.syncFolder(fileInformation, fileInformation.getName(), fileInformation.getParent(), exceptionHandler,
										itemView);
							}
							needUpdateFromServer = false;
							// refresh progress bar ui
							new Thread(new Runnable() {
								@Override
								public void run() {
									// mark as local cache
									for (int i = 0; i <= 100; i++) {
										Message message = new Message();
										message.what = UiConstant.FOLDER_IS_DOWNLOADDING;
										message.arg1 = 0;
										message.arg2 = i;
										downloadHandler.sendMessage(message);
										try {
											Thread.sleep(40);
										} catch (InterruptedException e) {
											// Auto-generated
											// catch
											// block
											e.printStackTrace();
										}
									}
								}
							}).start();
						} catch (ClientException e1) {
							// TODO Auto-generated catch block
							LogUtil.e(TAG, "Download login exception");
							e1.printStackTrace();
							Message msg_download = new Message();
							msg_download.what = UiConstant.FILE_DOWNLOAD_CANCEL; //
							msg_download.arg1 = 1;
							downloadHandler.sendMessage(msg_download);
						}
				}
			}).start();
		}

		public void downloadFileOrLogin(final iFileManager mdmTools) {
			new Thread(new Runnable() {
				@Override
				public void run() {
					try {
						// TODO
						// Auto-generated
						// method stub
						Actions actions = new Actions(context);
						actions.smartUpdateAuthiorzation();
						Message msg = new Message();
						msg.what = UiConstant.FILE_IS_DOWNLOADDING;
						msg.arg1 = 100;
						msg.arg2 = 1;
						msg.obj = PublicTools.changeBKM(Long.toString(fileInformation.getSize()));
						downloadHandler.sendMessage(msg);
						// TODO Auto-generated method stub
						boolean isDownload = true;
						if (null != cloudDriveService)
							isDownload = cloudDriveService.downloadFile(ShareDriveApplication.getInstance().getWnerID(), fileInformation.getParent(),
									fileInformation.getId(), ShareDriveApplication.getInstance().getAuthorization(), fileInformation.getSize(), path,
									downloadCallback, fileInformation);
						if (!isDownload) {
							Message msg_download = new Message();
							msg_download.what = UiConstant.FILE_DOWNLOAD_CANCEL; // download
							downloadHandler.sendMessage(msg_download);
						}
					} catch (ClientException e1) {
						// TODO Auto-generated catch block
						LogUtil.e(TAG, "Download login exception");
						e1.printStackTrace();
						Message msg_download = new Message();
						msg_download.what = UiConstant.FILE_DOWNLOAD_CANCEL; //
						msg_download.arg1 = 1;
						downloadHandler.sendMessage(msg_download);
						return;
					}
				}
			}).start();
		}

		/**
		 * @param myFileListAdapter
		 *            TODO
		 * **/
		void initFileSyncData() {
			refreshHandler.sendEmptyMessage(Constant.CLOUD_ADAPTER_HANDLER_FILEUI);
			// if it's file,refresh ui
			refreshHandler.sendEmptyMessage(Constant.CLOUD_ADAPTER_HANDLER_FILE_NOUPLOAD);// refresh
																							// fileUI
			try {
				FileInfo fileInfo = null;
				if (null != cloudDriveService)
					fileInfo = cloudDriveService.selectFile(fileInformation);
				if (null != fileInfo) {
					// if it's local cache
					if (fileInfo.isSync()) {
						Message message = new Message();
						message.what = UiConstant.INIT_VIEW_DOWNLOAD_STATE;
						downloadHandler.sendMessage(message);

						// check server if updated(use red pic warn)
						new Thread(new Runnable() {
							@Override
							public void run() {
								// TODO Auto-generated method stub
								boolean isUpdate = false;
								try {
									Actions actions = new Actions(context);
									actions.smartUpdateAuthiorzation();
									if (null != cloudDriveService)
										isUpdate = cloudDriveService.isServiceFileUpdate(context, fileInformation);
								} catch (ClientException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
								if (isUpdate) {
									needUpdateFromServer = true;
									Message msg = new Message();
									msg.what = UiConstant.CURRENT_ITEM_VIEW_NEED_UPLOAD;
									downloadHandler.sendMessage(msg);
								}

								int downloadTaskState = -1;
								if (null != cloudDriveService)
									downloadTaskState = cloudDriveService.downloadTaskState(fileInformation.getId());
								if (downloadTaskState == 0 || downloadTaskState == 1) {
									if (null != downloadTask) {
										try {
											downloadTask.setCallback(downloadCallback);
										} catch (Exception e) {
											// TODO: handle exception
											LogUtil.e(TAG, "download task set callback fail message:" + e.getLocalizedMessage());
										}
									}
									if (downloadTaskState == 1) {
										Message msg = new Message();
										msg.what = UiConstant.FILE_IS_DOWNLOADDING;
										msg.arg1 = 100;
										msg.arg2 = 1;
										downloadHandler.sendMessage(msg);
									}
								}
							}
						}).start();
					}
				}
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
		}

		private Handler refreshHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);
				//
				switch (msg.what) {
				case Constant.CLOUD_ADAPTER_HANDLER_INITUI:
					fileName.setText(fileInformation.getName());
					timeDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm");
					timeInfo = timeDateFormat.format(fileInformation.getModifiedAt());
					date.setText(timeInfo);
					//
					break;
				case Constant.CLOUD_ADAPTER_HANDLER_FILEUI:
					// TODO AAA
					window_more_collect_im.setBackgroundResource(R.mipmap.more_setting_synchronization);
					window_more_collect_tv.setText(context.getString(R.string.fileListadapter_keep));
					date.setVisibility(View.VISIBLE);
					// hide progress bar
					item_progress_horizontal.setVisibility(View.GONE);
					// display file size
					fileSize.setVisibility(View.VISIBLE);
					fileSize.setText(PublicTools.changeBKM(Long.toString(fileInformation.getSize())));
					break;
				case Constant.CLOUD_ADAPTER_HANDLER_FILE_ISUPLOAD:
					typeImg.setImageResource(R.mipmap.default_file_icon);
					// typeImg.setBackgroundResource(R.drawable.default_file_icon);
					// viewHolder.parentID = fileFolderInfo.getParent();
					date.setVisibility(View.GONE);
					item_progress_horizontal.setVisibility(View.VISIBLE);
					more_im.setBackgroundResource(R.mipmap.cancel_upload);
					break;
				case Constant.CLOUD_ADAPTER_HANDLER_FILE_NOUPLOAD:
					// TODO AAA
					typeImg.setImageResource(getTypeImgeID());
					break;

				case Constant.CLOUD_ADAPTER_HANDLER_FOLDERUI:
					date.setVisibility(View.VISIBLE);
					fileSize.setVisibility(View.GONE);
					item_progress_horizontal.setVisibility(View.GONE);
					window_more_collect_im.setBackgroundResource(R.mipmap.more_setting_synchronization);
					window_more_collect_tv.setText(context.getString(R.string.fileListadapter_keep));
					typeImg.setImageResource(R.mipmap.folder_im);
					// typeImg.setBackgroundResource(R.drawable.folder_im);
					break;

				default:
					break;
				}
			}
		};

		private Handler ahandler = new Handler() {
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case ClientExceptionRelateHandler.CLIENT_EXCEPTION_OCCURED:
					ClientException exception = (ClientException) msg.obj;
					Message eMsg = exceptionHandler.obtainMessage(exception.getStatusCode(), exception);
					eMsg.obj = itemView;
					eMsg.getData().putString("code", exception.getCode());
					eMsg.sendToTarget();
					break;

				case UiConstant.SUCCESS_GET_SHARED_USER_FOR_FILEFOLDER:
					ArrayList<SharedUser> shareADuserList = (ArrayList<SharedUser>) msg.obj;
					Intent intent = new Intent(context, ShareFileSearchActivity.class);
					intent.putExtra("sharedNodeInfo", fileInformation);
					intent.putExtra("userInfoList", shareADuserList);
					context.startActivity(intent);
					if (null != pwPopupWindow && pwPopupWindow.isShowing())
						pwPopupWindow.dismiss();
					break;

				default:
					break;
				}
			};
		};

		/**
		 * getTypeImgeID
		 * */
		private int getTypeImgeID() {
			// LogUtil.i(TAG, "getTypeImgeID...");
			int typeImgResId = R.mipmap.default_file_icon;
			if (PublicTools.isFileType(fileInformation.getName(), Constant.WORD_TYPE)) {
				typeImgResId = R.mipmap.doc;
			} else if (PublicTools.isFileType(fileInformation.getName(), Constant.PPT_TYPE)) {
				typeImgResId = R.mipmap.ppt;
			} else if (PublicTools.isFileType(fileInformation.getName(), Constant.IMAGE_TYPE)) {
				typeImgResId = R.mipmap.empty_pic;
				try {
					// TODO Auto-generated method stub
					// LogUtil.i(TAG, "[getTypeImgeID] fileType is image...");
					String iconPath = DirectoryUtil.genThumbnailFileFullName(context, fileInformation.getOwnerBy(), fileInformation.getId(),
							fileInformation.getName());
					File thumBnail2 = new File(iconPath);
					fileIconPath = iconPath;
					if (!thumBnail2.exists() && null != cloudDriveService) {
						cloudDriveService.downloadThumbnailIcon(fileInformation.getOwnerBy(), fileInformation.getId(), iconPath, downloadThumbnailCallback);
					} else {
						Message msg_download = new Message();
						msg_download.what = UiConstant.THUMBNAIL_DOWNLOAD_SUCCESS;
						downloadHandler.sendMessage(msg_download);
					}
				} catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
					LogUtil.e(TAG, "[getTypeImgeID] fileType is image that show fail..." + e.getLocalizedMessage());
				}
			} else if (PublicTools.isFileType(fileInformation.getName(), Constant.RAR_TYPE)) {
				typeImgResId = R.mipmap.rar;
			} else if (PublicTools.isFileType(fileInformation.getName(), Constant.ZIP_TYPE)) {
				typeImgResId = R.mipmap.rar;
			} else if (PublicTools.isFileType(fileInformation.getName(), Constant.VIDEO_TYPE)) {
				typeImgResId = R.mipmap.video;
			} else if (PublicTools.isFileType(fileInformation.getName(), Constant.MUSIC_TYPE)) {
				typeImgResId = R.mipmap.music;
			} else if (PublicTools.isFileType(fileInformation.getName(), Constant.TXT_TYPE)) {
				typeImgResId = R.mipmap.txt;
			} else if (PublicTools.isFileType(fileInformation.getName(), Constant.PDF_TYPE)) {
				typeImgResId = R.mipmap.pdf;
			} else if (PublicTools.isFileType(fileInformation.getName(), Constant.EXCEL_TYPE)) {
				typeImgResId = R.mipmap.excel;
			} else {
				typeImgResId = R.mipmap.default_file_icon;
			}
			return typeImgResId;
		}

		/**
		 * @param myFileListAdapter
		 *            TODO
		 * **/
		void initFolderSyncData() {
			// TODO Auto-generated method stub
			refreshHandler.sendEmptyMessage(Constant.CLOUD_ADAPTER_HANDLER_FOLDERUI);
			// new Thread(new Runnable() {
			// @Override
			// public void run() {
			// TODO Auto-generated method stub
			try {
				FolderInfo folderInfo = null;
				if (null != cloudDriveService)
					folderInfo = cloudDriveService.selectFolder(fileInformation);
				if (null != folderInfo) {
					if (folderInfo.isSync()) {
						Message message = new Message();
						message.what = UiConstant.INIT_VIEW_DOWNLOAD_STATE;
						downloadHandler.sendMessage(message);

						new Thread(new Runnable() {
							@Override
							public void run() {
								// TODO Auto-generated method stub
								boolean isUpdate = false;
								try {
									Actions actions = new Actions(context);
									actions.smartUpdateAuthiorzation();
									if (null != cloudDriveService)
										isUpdate = cloudDriveService.isServiceUpdate(context, fileInformation);
								} catch (ClientException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
								if (isUpdate) {
									needUpdateFromServer = true;
									Message msg = new Message();
									msg.what = UiConstant.CURRENT_ITEM_VIEW_NEED_UPLOAD;
									downloadHandler.sendMessage(msg);
								}
							}
						}).start();
					}
				}
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
		}

		/**
		 * init downloadtask
		 * 
		 * @param myFileListAdapter
		 *            TODO
		 * @param fileId
		 *            TODO
		 * */
		void initDownloadTask() {
			// TODO Auto-generated method stub
			new Thread(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					// LogUtil.i(TAG, "initDownloadTask...");
					try {
						if (null != cloudDriveService) {
							DownloadTask dt = cloudDriveService.getDownloadTask(fileInformation.getId());
							downloadTask = dt;
						}
					} catch (Exception e) {
						// TODO: handle exception
						e.printStackTrace();
						downloadTask = null;
						LogUtil.e(TAG, "initDownloadTask fail..." + e.getLocalizedMessage());
					}
				}
			}).start();
		}

	}

	private void initMDMFile() {

		// new Thread(new Runnable() {
		// @Override
		// public void run() {
		// TODO Auto-generated method stub
		LogUtil.i(TAG, "init MDMFile...");
		// TODO Auto-generated method stub]
		try {
			String[] filePath = { DirectoryUtil.getCurrentCachePath(context) + ClientConfig.CACHE_CONTEXT + PublicTools.getClientUserName(context) };
			iFileManager mdmTools = FileManagerFactory.getFileManager(context);
			for (int i = 0; i < filePath.length; i++) {
				if (!mdmTools.fileIsExist(filePath[i])) {
					mdmTools.createFilePath(filePath[i]);
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			LogUtil.e(TAG, "initMDMFile fail..." + e.getLocalizedMessage());
		}
		// }
		// }).start();
	}

}
